package com.youdoneed.user.job;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.querydsl.sql.dml.SQLUpdateClause;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.base.pagination.Paging;
import com.youdoneed.user.application.QueryHelper;
import com.youdoneed.user.model.Job;
import com.youdoneed.user.query.QJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * 职业服务实现类。
 *
 * @author Ewing
 * @date 2017.2.8
 */
@Service
@Transactional
public class JobServiceImpl implements JobService {
    private final Logger logger = LoggerFactory.getLogger(JobServiceImpl.class);

    @Autowired
    private SQLQueryFactory queryFactory;

    private QJob qJob = QJob.Job;

    /**
     * 添加职业。
     */
    @Override
    public long addJob(Job job) {
        if (job == null || !StringUtils.hasText(job.getName())) {
            throw new AppException("Job info is empty.");
        }
        job.setJobId(GlobalIdWorker.nextString());
        job.setCreateTime(new Date());
        // 在最大顺序上加1
        Integer maxSort = queryFactory.select(qJob.sort.max())
                .from(qJob)
                .fetchOne();
        if (maxSort == null) {
            job.setSort(1);
        } else {
            job.setSort(maxSort + 1);
        }
        return queryFactory.insert(qJob)
                .populate(job)
                .execute();
    }

    /**
     * 根据ID获取职业。
     */
    @Override
    public Job getJob(String jobId) {
        if (!StringUtils.hasText(jobId)) {
            throw new AppException("职业ID为空。");
        }
        return queryFactory.selectFrom(qJob)
                .where(qJob.jobId.eq(jobId))
                .fetchOne();
    }

    /**
     * 根据条件查询职业。
     */
    @Override
    public Page<Job> findJobs(Paging paging, String name) {
        SQLQuery<Job> query = queryFactory.selectFrom(qJob)
                .orderBy(qJob.sort.asc());
        if (StringUtils.hasText(name)) {
            query.where(qJob.name.contains(name));
        }
        return QueryHelper.queryPage(paging, query);
    }

    /**
     * 删除职业。
     */
    @Override
    public long deleteJob(String jobId) {
        if (!StringUtils.hasText(jobId)) {
            throw new AppException("职业ID为空。");
        }
        return queryFactory.delete(qJob)
                .where(qJob.jobId.eq(jobId))
                .execute();
    }

    /**
     * 更新职业。
     */
    @Override
    public long updateJob(Job job) {
        if (job == null || !StringUtils.hasText(job.getJobId())) {
            throw new AppException("Job info is empty.");
        }
        SQLUpdateClause update = queryFactory.update(qJob)
                .populate(job)
                .where(qJob.jobId.eq(job.getJobId()));
        return update.isEmpty() ? 0L : update.execute();
    }

    /**
     * 获取显示的职业。
     */
    @Override
    public List<Job> showJobs() {
        return queryFactory.selectFrom(qJob)
                .where(qJob.state.eq(1))
                .orderBy(qJob.sort.asc())
                .fetch();
    }

    @Override
    public long sortMoveUp(String jobId) {
        if (!StringUtils.hasText(jobId)) {
            throw new AppException("职业ID为空。");
        }
        Job job = getJob(jobId);
        // 取前一条
        Job preJob = queryFactory.selectFrom(qJob)
                .where(qJob.sort.lt(job.getSort()))
                .orderBy(qJob.sort.desc())
                .fetchFirst();
        if (preJob == null) {
            throw new AppException("已经到顶了。");
        }
        return swapSort(preJob, job);
    }

    @Override
    public long sortMoveDown(String jobId) {
        if (!StringUtils.hasText(jobId)) {
            throw new AppException("职业ID为空。");
        }
        Job job = getJob(jobId);
        // 取后一条
        Job nextJob = queryFactory.selectFrom(qJob)
                .where(qJob.sort.gt(job.getSort()))
                .orderBy(qJob.sort.asc())
                .fetchFirst();
        if (nextJob == null) {
            throw new AppException("已经到底了。");
        }
        return swapSort(nextJob, job);
    }

    /**
     * 交换顺序。
     */
    public long swapSort(Job jobIdA, Job jobIdB) {
        SQLUpdateClause update = queryFactory.update(qJob);
        update.set(qJob.sort, jobIdA.getSort())
                .where(qJob.jobId.eq(jobIdB.getJobId()))
                .addBatch();
        update.set(qJob.sort, jobIdB.getSort())
                .where(qJob.jobId.eq(jobIdA.getJobId()))
                .addBatch();
        return update.execute();
    }

}
